﻿
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using Newtonsoft.Json;
using Ec_System.WebUI.Models;

namespace Ec_System.WebUI
{
    public class UserHelp
    {
        /// <summary>
        /// 获取存放在Cookie里的用户信息
        /// </summary>
        /// <returns>LoginViewModel</returns>
        public LoginViewModel TryGetUserInfo()
        {
            try
            {
                LoginViewModel info = null;

                HttpContext context = HttpContext.Current;
                if (context == null)
                    throw new ArgumentNullException();

                //读取cookie
                HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie == null || string.IsNullOrWhiteSpace(cookie.Value))
                    return null;

                //获取cookie信息并且解析
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
                if (ticket != null && !string.IsNullOrWhiteSpace(ticket.UserData))
                {
                    info = JsonConvert.DeserializeObject<LoginViewModel>(ticket.UserData);

                }

                return info;
            }
            catch(Exception ex)
            {
                return null;
            }

        }
    }
}